package jadeCW;


import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

import java.util.HashMap;

public class HospitalAgent extends Agent {

	private int noAvailableAppointments;
	private HashMap<String, Integer> agentToAppointment = new HashMap<String, Integer>();

	protected void setup() {

		System.out.println("Hospital-Agent " + getAID().getName() + " is ready.");

		Object[] args = getArguments();

		if (args != null && args.length > 0) {
			// read in input argument - integer as number of availbale appointments
			noAvailableAppointments = (Integer) args[0];

			// register appointment service to yellow pages
			DFAgentDescription dfd = new DFAgentDescription();
			dfd.setName(getAID());
			ServiceDescription sd = new ServiceDescription();
			sd.setType("allocate-appointments");
			sd.setName("Hospital appointment allocation system");
			dfd.addServices(sd);
			try {
				DFService.register(this, dfd);
			}
			catch (FIPAException e) {
				e.printStackTrace();
			}

		}
		else {
			System.out.println("No number of appointments specified");
		}

	}

	protected void takeDown() {

		// deregister from yellow pages
		try {
			DFService.deregister(this);
			// print Appointments
			for (String key : agentToAppointment.keySet()) {
				System.out.println("Hospital1:  Appointment " + agentToAppointment.get(key) + " is allocated to patient " + key);
			}

		}
		catch (FIPAException e) {
			e.printStackTrace();
		}
		System.out.println("Buyer-Agent " + getAID().getName() + " terminating.");
	}

	private class AllocateAppointment extends CyclicBehaviour {

		@Override
		public void action() {

			// TODO add template
			// 1. receive template for an appointment
			ACLMessage receive = myAgent.receive();

			if (receive != null) {
				ACLMessage reply = receive.createReply();
				// check if an appointment is available
				if (noAvailableAppointments > 0) {
					// make any appointment and agree
					reply.setPerformative(ACLMessage.AGREE);
					reply.setContent(String.valueOf(noAvailableAppointments));
					// Update which agent has which appointment
					agentToAppointment.put(receive.getSender().toString(), noAvailableAppointments);
					noAvailableAppointments--;
				}
				else {
					// send refuse
					reply.setPerformative(ACLMessage.REFUSE);
					reply.setContent("not-Available");
				}
				myAgent.send(reply);

			}

		}

	}
}
